package com.p7.notepad.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.p7.notepad.R;
import com.p7.notepad.app.BaseActivity;
import com.p7.notepad.bean.NotepadDetails;
import com.p7.notepad.bean.NotepadInfo;
import com.p7.notepad.bean.Success;
import com.p7.notepad.network.APIManager;
import com.p7.notepad.network.exception.ExceptionHandle;
import com.p7.notepad.network.listener.RequestListener;
import com.p7.notepad.tools.Storage;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class NotepadDetailsActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.notepad_details_title_page)
    TextView mTitlePage;
    @BindView(R.id.notepad_details_file_name)
    TextView mFileName;
    @BindView(R.id.notepad_details_title)
    TextView mTitle;
    @BindView(R.id.notepad_details_collect)
    CheckBox mCollect;
    @BindView(R.id.notepad_details_web)
    WebView mWeb;

    private String id;

    @Override
    public int getLayoutId() {
        return R.layout.activity_notepad_details;
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        Bundle bundle = getIntent().getBundleExtra("bundle");
        id = bundle.getString("id");
        initWebFile();
        mCollect.setOnCheckedChangeListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getNotepad();
    }

    private void initWebFile() {
        WebSettings webSettings = mWeb.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setTextZoom(260);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        mWeb.setInitialScale(100);
        mWeb.setWebViewClient(new WebViewClient());
    }

    private void getHtml(String text) {
        if (!TextUtils.isEmpty(text)) {
            String html = "";
            List<NotepadInfo> data = new Gson().fromJson(text, new TypeToken<List<NotepadInfo>>() {}.getType());
            for (NotepadInfo info : data) {
                if (!TextUtils.isEmpty(info.getInput())) {
                    html = html + "<p class=\"p\"><span style=\"font-family:微软雅黑;color:#2E2E2E;font-size:13.5000pt;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                            + info.getInput() + " </span></p>";
                }
                if (!TextUtils.isEmpty(info.getUrl())) {
                    html = html + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"" + info.getUrl() + "\" />";
                }
            }
            html =  "<html><body>" + html + "</body></html>";
            mWeb.loadDataWithBaseURL(null, html, "text/html","utf-8",null);
        }
    }

    @OnClick({R.id.notepad_details_quit, R.id.notepad_details_preserve, R.id.notepad_details_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.notepad_details_quit:
                finish();
                break;
            case R.id.notepad_details_preserve:
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                bundle.putString("info", info);
                bundle.putString("name", name);
                bundle.putString("fileId", fileId);
                startActivity(EditNotepadActivity.class, bundle);
                break;
            case R.id.notepad_details_del:
                getDel();
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            collectNotepad();
        } else {
            cancelCollect();
        }
    }

    private void collectNotepad() {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("notepadId", id);
        parameters.put("userId", String.valueOf(Storage.getId()));
        APIManager.onPost("notepad/collectNotepad", parameters, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                Success success = gson.fromJson(s, Success.class);
                if (success.getCode() == 1000) {
//                    setToast("收藏成功");
                } else if (success.getCode() == 2001) {
                    setCollect(false);
                    startActivity(LoginActivity.class);
                } else {
                    setToast("网络加载失败，请稍后重试");
                    setCollect(false);
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast("网络加载失败，请稍后重试");
                setCollect(false);
            }
        });
    }

    private void cancelCollect() {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("notepadId", id);
        parameters.put("userId", String.valueOf(Storage.getId()));
        APIManager.onPost("notepad/cancelCollect", parameters, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                Success success = gson.fromJson(s, Success.class);
                if (success.getCode() == 1000) {
//                    setToast("取消收藏成功");
                } else if (success.getCode() == 2001) {
                    setCollect(true);
                    startActivity(LoginActivity.class);
                } else {
                    setToast("网络加载失败，请稍后重试");
                    setCollect(true);
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast("网络加载失败，请稍后重试");
                setCollect(true);
            }
        });
    }

    private void getDel() {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("id", id);
        APIManager.onPost("notepad/delNotepad", parameters, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                Success success = gson.fromJson(s, Success.class);
                if (success.getCode() == 1000) {
                  setToast("记事本删除成功");
                  finish();
                } else if (success.getCode() == 2001) {
                    startActivity(LoginActivity.class);
                } else {
                    setToast("网络加载失败，请稍后重试");
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast("网络加载失败，请稍后重试");
            }
        });
    }

    private String name;
    private String info;
    private String fileId;
    private void getNotepad() {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("id", id);
        APIManager.onPost("notepad/getSingleNotepad", parameters, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                NotepadDetails notepad = gson.fromJson(s, NotepadDetails.class);
                if (notepad.getCode() == 1000) {
                    mTitle.setText(notepad.getData().getNotepad().getTitle());
                    name = notepad.getData().getNotepad().getTitle();
                    fileId = String.valueOf(notepad.getData().getNotepad().getFolderId());
                    info = notepad.getData().getNotepad().getInfo();
                    setCollect(notepad.getData().getIsCollect() == 1 ? true : false);
                    getHtml(notepad.getData().getNotepad().getInfo());
                } else if (notepad.getCode() == 2001) {
                    startActivity(LoginActivity.class);
                } else {
                    setToast("网络加载失败，请稍后重试");
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast("网络加载失败，请稍后重试");
            }
        });
    }

    private void setCollect(boolean flag) {
        mCollect.setOnCheckedChangeListener(null);
        mCollect.setChecked(flag);
        mCollect.setOnCheckedChangeListener(this);
    }

    private void setToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

}
